package com.com.effectivejava.generalprogramming;

/**
 * Created by User on 10/07/2014.
 */
public class MutableArray {
    // Notes: Final reference to a mutable array.
    public static final int [] UNSAFE_PRIVATE_VALUES = initializeArray();
    public static final int [] SAFE_PRIVATE_VALUES = initializeArray();

    public static int[] initializeArray(){
        return new int [] {0, 1, 2, 3};
    }


    // Dangerous to return the final reference
    // to an array.
    public static int[] getUnsafePrivateValues(){
        return UNSAFE_PRIVATE_VALUES;
    }
    // Not really an outsider to a class. but makes the point.
    public static void illegalAccessToUnsafeVlaues(){
        int [] danger = getUnsafePrivateValues();
        danger[2] =100;
    }

    //Safe guarded
    public static int[] getPrivateValuesInSafeManner(){
        return SAFE_PRIVATE_VALUES.clone();
    }
   // Not really an outsider to a class. but makes the point.
    public static void illegalAccessToSafeValues(){
        int [] danger = getPrivateValuesInSafeManner();
        danger[2] =100;
    }


    public  static void  printPrivateValues(int[] values ){
        System.out.print("\n Array: ");
        for(int i : values ){
            System.out.print(i+" ,");
        }
    }

    public static void main(String[] args) {
        printPrivateValues(UNSAFE_PRIVATE_VALUES);
        //Danger: Mutable Array object for a final reference.
        illegalAccessToUnsafeVlaues();
        printPrivateValues(UNSAFE_PRIVATE_VALUES);


        printPrivateValues(SAFE_PRIVATE_VALUES);
        //This time its safe guarded.
        illegalAccessToSafeValues();
        printPrivateValues(SAFE_PRIVATE_VALUES);
    }


}
